/**
 * Desc
 * @description Holp You Do Good But Not Evil
 * @copyright   Copyright 2014-2015 <ycchen@iwshop.cn>
 * @license     LGPL (http://www.gnu.org/licenses/lgpl.html)
 * @author      Chenyong Cai <ycchen@iwshop.cn>
 * @package     Wshop
 * @link        http://www.iwshop.cn
 */

/**
 * 当前客户id
 * @type Number
 */
var currCid = 0;

/**
 * 已加载页
 * @type Number
 */
var loaded = 0;

/**
 * 目前card页码
 * @type Number
 */
var currComp = 0;

/**
 * 提前加载页码
 * @type Number
 */
var pageNo = 0;

var cusIds = false;

requirejs(['config'], function (config) {

    require(['jquery', 'util', 'journal', 'customer', 'Cardlist', 'fancyBox', 'ueditor', 'jUploader', 'Spinner'], function ($, util, Journal, Customer, Cardlist, fancyBox, ueditor, jUploader, Spinner) {

        var frame = $('#inframe');

        $(document).on('keyup', function (e) {
            var currKey = 0, e = e || event;
            currKey = e.keyCode || e.which || e.charCode;
            rollPage(currKey);
        });

        window.rollPage = function (currKey) {
            if (currKey === 37) {
                pageLeft();
            }
            if (currKey === 39) {
                pageRight();
            }
        };

        function pageLeft() {
            if (currComp >= 1) {
                config.endOfCard = false;
                loadPage(cusIds[--currComp]);
                currCid = cusIds[currComp];
                updateCid();
            } else {
                util.Alert('There is no more', true);
            }
        }

        function pageRight() {
            if (!config.endOfCard) {
                loadPage(cusIds[++currComp]);
                currCid = cusIds[currComp];
                config.endOfCard = false;
            } else {
                util.Alert('There is no more', true);
            }
        }

        /**
         * 页面预加载
         * @param {type} cusId
         * @returns {undefined}
         */
        window.loadPage = function (cusId) {
            if (!config.endOfCard && cusId !== undefined) {
                $('#inframeLoading').show();
                Spinner.spin($('#inframeLoading').get(0));
                frame.attr('src', '?/Profile/view/id=' + cusId);
            }
        }

        window.frameOnload = function () {
            $('#inframeLoading').hide();
        };

        /**
         * 刷新Cid变量
         * @returns {undefined}
         */
        function updateCid() {
            // 直接从card元素取值data-id
            currCid = parseInt($('.card').eq(currComp).attr('data-id'));
        }

        util.onresize(function () {
            $('#inframe').height($(window).height() - 50);
        });

//        $('#nav-addcustomer').click(function () {
//            $('.addProfile').eq(0).click();
//        });

        


        Spinner.spin($('#sec').get(0));

        Customer.getCuslistId(function (r) {
            cusIds = r;
            loadPage(r[0]);
        });

    });

});